package com.newlink.building.common_base.base

import android.text.TextUtils
import android.view.View
import com.newlink.building.common_base.ext.showToastImmediately
import com.newlink.building.common_base.ext.showToastLong
import com.newlink.building.common_base.utils.DialogUtil

/**
 * Created by xiaodong on 2022/7/25.
 */
@Suppress("UNCHECKED_CAST")
abstract class BaseMvpFragment<in V : IView, P : IPresenter<V>> : BaseFragment(), IView {

    /**
     * Presenter
     */
    protected var mPresenter: P? = null

    protected abstract fun createPresenter(): P

    override fun initData() {
        mPresenter = createPresenter()
        mPresenter?.attachView(this as V)
    }

    override fun initView(view: View) {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mPresenter?.detachView()
        this.mPresenter = null
        if (mDialog.isShowing) {
            mDialog.dismiss()
        }
    }

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(requireContext())
    }

    override fun showLoading() {
        mDialog.show()
    }

    override fun hideLoading() {
        mDialog.dismiss()
    }

    override fun showError(errorMsg: String) {
        showToastImmediately(errorMsg)
    }

    override fun showDefaultMsg(msg: String) {
        if (TextUtils.isEmpty(msg)) {
            return
        }
        showToastLong(msg)
    }

    override fun showMsg(msg: String) {
        showToastImmediately(msg)
    }
}
